import fs from 'fs';
import path from 'path';
import * as nanoid from 'nanoid';
import dayjs from 'dayjs';
import OSS from 'ali-oss';
import { fileURLToPath } from 'url';
import MarkdownToWord from '../plugins/md2word/wordPlugin.js';
import config from '../config/index.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const tempDir = path.join(__dirname, "..", "temp");

// 确保临时目录存在
if (!fs.existsSync(tempDir)) {
  fs.mkdirSync(tempDir);
}

// 配置阿里云OSS客户端
const ossClient = new OSS(config.oss);

export async function convertMarkdownToWord(req, res) {
  try {
    const { content, fileName } = req.body;
    if (!content) {
      return res.status(400).json({ error: "需要提供Markdown内容" });
    }

    // 生成临时文件名
    const timestamp = dayjs().valueOf();
    const randomString = nanoid.nanoid(6);
    if (!fileName) {
      fileName = `${timestamp}_${randomString}`;
    }

    // 创建临时文件路径
    const tempMdPath = path.join(tempDir, `${fileName}.md`);
    const tempDocxPath = path.join(tempDir, `${fileName}.docx`);

    // 写入Markdown内容
    fs.writeFileSync(tempMdPath, content);

    // 转换为Word文档
    const converter = new MarkdownToWord();
    const success = await converter.convert(tempMdPath, tempDocxPath);

    if (!success) {
      throw new Error("文档转换失败");
    }

    // 上传到OSS
    const ossPath = `documents/${fileName}.docx`;
    const result = await ossClient.put(ossPath, fs.readFileSync(tempDocxPath));

    // 清理临时文件
    fs.unlinkSync(tempMdPath);
    fs.unlinkSync(tempDocxPath);
    let url = result.url.replace("http:", "https:");

    res.json({
      code: 1000,
      data: {
        url,
        path: ossPath,
      },
      message: "转换成功",
    });
  } catch (error) {
    console.error("文档处理失败:", error);
    res.json({
      code: 1001,
      message: "文档转换失败",
    });
  }
}
